//
//  XTRefreshControl.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/18.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit
enum RefreshState:Int{
    //下拉刷新
    case Normal = 0
    //释放刷新
    case Pulling = 1
    //精选推荐中
    case Refreshing = 2
}

class XTRefreshControl: UIControl {
    
    var currentScrollState:RefreshState = .Normal{
        didSet{
            switch currentScrollState{
            case .Normal:
                print("Normal")
                messageLabel.text = "下拉刷新"
                iconView.hidden = false
                indicatorView.stopAnimating()
                //重置箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformIdentity
                })
                if oldValue == .Refreshing{
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top -= 50
                })
                }
                
            case .Pulling:
                print("Pulling")
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                print("Refreshing")
                messageLabel.text = "精选推荐中"
                iconView.hidden = true
                indicatorView.startAnimating()
                //给观察者发送“ValueChanged”的状态，使其执行监听实现方法
                sendActionsForControlEvents(.ValueChanged)
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += 50
                })
                
            }
        }
    
    }
    
        //  MARK: -懒加载控件-
    //箭头
    private lazy var iconView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //菊花转
    private lazy var indicatorView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    //文字
    private lazy var messageLabel:UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fronSize: 12)
        label.text = "下拉刷新"
        return label
    }()
       
    
    
    var currentScrollView : UIScrollView?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    private func setupUI(){
    backgroundColor = UIColor.redColor()
        
        addSubview(iconView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(iconView)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.leading.equalTo(iconView.snp_trailing)
        }
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        print(newSuperview)
        
        
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        //添加kvo监听
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        currentScrollView = scrollView
        
        //设置frame
        frame.size.width = currentScrollView!.frame.size.width
        frame.size.height = 50
        frame.origin.y = -50
        
    }
    //kvo监听执行的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(currentScrollView?.contentOffset.y)
        
        if currentScrollView!.dragging {
            //拖动情况下有两种状态
            //1.下拉刷新
            //2.释放刷新
            //从“下拉刷新”进入“释放刷新”的临界值
            let maxY = -(currentScrollView!.contentInset.top + 50)
            let contentOffsetY = currentScrollView?.contentOffset.y
            //注意此处两者都为负数
            if contentOffsetY < maxY && currentScrollState == .Normal{
                //由normal进入pulling
                currentScrollState = .Pulling
            
            }else if(contentOffsetY >= maxY) && currentScrollState == .Pulling{
            
                //由pulling进入normal
                currentScrollState = .Normal
            }
        }else{
        
            //松手状态下，若前一状态为释放刷新，则接下来就是“精选推荐中”
            if currentScrollState == .Pulling{
                currentScrollState = .Refreshing
            }
        }
        
    }
    
    func endRefresh(){
        currentScrollState = .Normal
    }
    
    deinit{
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
